<template>
    <div class="containerBox">
        <el-button-group>
            <el-button type="primary" @click="returnFormModel"><i class="el-icon-back"></i>模型管理</el-button>
            <el-button type="primary" @click="handleUndo"><i class="el-icon-caret-left"></i>后退</el-button>
            <el-button type="primary" @click="handleRedo"><i class="el-icon-caret-right"></i>前进</el-button>
            <el-button type="warning" @click="handleDownload"><i class="el-icon-download"></i>下载BPMN</el-button>
            <el-button type="success" @click="saveDesignProcessModel"><i class="el-icon-position"></i>保存</el-button>
            <el-upload
                    style="display: inline-block;"
                    :file-list="fileList"
                    class="upload-demo"
                    action=""
                    :auto-upload="false"
                    :show-file-list="false"
                    :http-request="httpRequest"
                    :on-change="handleOnchangeFile"
                    :on-remove="handleRemove"
                    :before-remove="beforeRemove"
            >
                <el-button type="danger"><i class="el-icon-link"></i>导入</el-button>
            </el-upload>
        </el-button-group>
        <!-- 主要内容 -->
        <div id="container"></div>
        <!-- 属性面板 -->
        <div id="js-properties-panel" class="panel"></div>
    </div>
</template>
<script>
    import BpmnModeler from 'bpmn-js/lib/Modeler';
    import propertiesPanelModule from 'bpmn-js-properties-panel'
    import propertiesProviderModule from 'bpmn-js-properties-panel/lib/provider/camunda'
    import camundaExtension from './panel/camunda';
    import customTranslate from './customTranslate/customTranslate';
    import { initXml } from '../innerModel/mock/initXml'
    export default {
        name: 'DrowProccessImageInnerInner',
        data() {
            return {
                containerEl: null,
                bpmnModeler: null,
                fileList: [],
                DesignProcessModelVO:{
                    bpmnXml:'',
                    svgXml:'',
                    actReModelId:''
                }
            };
        },
        mounted() {
            var customTranslateModule = {
            　　translate: [ 'value', customTranslate ]
        　　};
            // 获取到属性id为“container”的dom节点
            this.containerEl = document.getElementById('container');
            // 创建模型
            this.bpmnModeler = new BpmnModeler({
                // 添加内容面板
                container: this.containerEl,
                // 添加属性控制板
                propertiesPanel: {
                    parent: '#js-properties-panel'
                },
                // 面板扩展
                moddleExtensions: {
                    camunda: camundaExtension
                },
                // 额外的面板
                additionalModules: [
                    // 左边工具栏以及节点（自定义）
                    propertiesProviderModule,
                    // 右边的工具栏(属性)
                    propertiesPanelModule,
                    // 中文翻译
                    customTranslateModule
                ]
            });
            this.create();
        },
        methods: {
            // 保存
            saveDesignProcessModel(){
                this.bpmnModeler.saveXML({format: true}, (err, data) => {
                    this.DesignProcessModelVO.bpmnXml = data.replace(new RegExp('camunda:','g'),'activiti:');
                    this.bpmnModeler.saveSVG({format: true}, (err, data) => {
                        this.DesignProcessModelVO.svgXml = data;
                        this.putRequest("/activity/ActReModel/update/DesignProcessModel", this.DesignProcessModelVO).then(resp => {
                            if (resp) {
                                
                            }
                        })
                    })
                })
            },
            // 返回流程模型管理
            returnFormModel(){
                this.$router.push('/workflowActReModel');
            },
            // 创建
            create() {
                this.DesignProcessModelVO.actReModelId = this.$route.query.modelId;
                this.getRequest("/activity/ActReModel/query/ProcessModelXMLInformationByModelId/"+this.DesignProcessModelVO.actReModelId).then(resp => {
                    if (resp) {
                        let dataXml = resp.data.replace(new RegExp('activiti:','g'),'camunda:');
                        // 将字符串转换成图显示出来
                        this.bpmnModeler.importXML(dataXml, (err) => {
                            if (err) {
                                // console.error(err)
                            }else {
                                // 这里是成功之后的回调, 可以在这里做一系列事情
                                this.success();
                            }
                        })
                    }else{
                        // 将字符串转换成图显示出来
                        this.bpmnModeler.importXML(initXml, (err) => {
                            if (err) {
                                // console.error(err)
                            }else {
                                // 这里是成功之后的回调, 可以在这里做一系列事情
                                this.success();
                            }
                        })
                    }
                });
            },
            success () {
                // console.log('创建成功!')
                // this.addEventBusListener()
            },
            // 移除流程文件
            handleRemove(file) {
                for (let i = 0; i < this.fileList.length; i++) {
                    if (file.name === this.fileList[i].name) {
                        this.fileList.splice(i, 1);
                    }
                }
            },
            // 移除流程文件提示信息
            beforeRemove(file) {
                return this.$confirm(`确定移除 ${file.name}？`);
            },
            // 后退
            handleUndo() {
                this.bpmnModeler.get('commandStack').undo();
            },
            // 前进
            handleRedo() {
                this.bpmnModeler.get('commandStack').redo();
            },
            // 下载流程文件
            handleDownload() {
                this.bpmnModeler.saveXML({format: true}, (err, data) => {
                    // 替换camunda:和activiti:
                    const dataXml = data.replace(new RegExp('camunda:','g'),'activiti:');
                    const dataTrack = 'bpmn';
                    const a = document.createElement('a');
                    const name = `diagram.${dataTrack}`;
                    a.setAttribute(
                        'href',
                        `data:application/bpmn20-xml;charset=UTF-8,${encodeURIComponent(dataXml)}`
                    );
                    a.setAttribute('target', '_blank');
                    a.setAttribute('dataTrack', `diagram:download-${dataTrack}`);
                    a.setAttribute('download', name);
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                });
            },
            httpRequest(){

            },
            // 导入流程文件
            handleOnchangeFile(file) {
                const reader = new FileReader();
                let data = '';
                reader.readAsText(file.raw);
                reader.onload = (event) => {
                    data = event.target.result;
                    this.bpmnModeler.importXML(data, (err) => {
                        if (err) {
                            this.$message.info('导入失败');
                        } else {
                            this.$message.success('导入成功');
                        }
                    });
                };
            }
        }
    }
</script>
<style lang="scss">
    // 整个箱子
    .containerBox {
        height: calc(100vh - 20px);
        position: relative;
    // 主要内容
    #container {
            height: calc(100% - 50px);
        }
    }
    // 属性面板
    .panel{
        position: absolute;
        right: 0;
        top: 0;
        width: 300px;
    }
    // 隐藏logo
    .bjs-powered-by {
        visibility: hidden;
    }
</style>